package yf.platform.biz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.yfsoft.comm.util.TimeUtil;

import yf.platform.bo.BizResult;
import yf.platform.ctl.GlobalKey;



/**
 * 工作流服务组件
 * @author Sail
 *
 */
public class WorkflowService extends TplService {

	@Override
	public BizResult form(Map<String,String> input) throws Throwable{
		//加载发布状态下拉框
		List<Map<String,Object>> status = this.getDataSource("ds_name","流程发布状态");
		rst.setReqAttribute("status",status );
		//加载部门信息
		List<Map<String,Object>> obs = this.daoSupport.find("usr_obs", "o_id,o_name", null, null);
		rst.setReqAttribute("obs",obs );
		rst.setReqAttribute("p", input.get("p"));
		//加载模板信息
		if("edit".equals(input.get("p"))){
			String e_id = input.get("key");
			Map<String,Object> e = this.daoSupport.findOne("wf_tpl",null,"t_id = "+e_id);
			List<Map<String,Object>> nodes = this.daoSupport.find("wf_node", null, "n_tpl = "+e_id, "n_code");
			rst.setReqAttribute("e",e )
				.setReqAttribute("nodes", nodes)
				.setReqAttribute("key", e_id);
		}
		return rst.setCode(0).setType(BizResult.REDIRECT).setPage("WIDGETS/WF/tpl_form.jsp");
	}

	/**
	 * 采用AJAX的方式来新建流程模板
	 * @param input
	 * @return
	 */
	public BizResult addTpl(Map<String,String> input){
		int id = this.daoSupport.insert( "wf_tpl",input);
		rst.setData(id);
		return rst.setType(BizResult.ECHO)
				.setCode(0);
	}
	
	/**
	 * 采用AJAX的方式来修改流程模板
	 * @param input
	 * @return
	 */
	public BizResult editTpl(Map<String,String> input){
		int row = this.daoSupport.update(input, "t_id = " + input.get("t_id"),  "wf_tpl");
		if(row != 1){
			rst.setCode(-101).setMsg("影响行数超出预期值,共影响了："+row);
		}
		return rst.setType(BizResult.ECHO)
				.setCode(0);
	}
	
	/**
	 * 采用AJAX的方式来新建流程模板的节点
	 * @param input
	 * @return
	 */
	public BizResult addNode(Map<String,String> input){
		int row = this.daoSupport.insert("wf_node",input);
		if(row != 1){
			rst.setCode(-101).setMsg("影响行数超出预期值,共影响了："+row);
		}
		return rst.setType(BizResult.ECHO)
				.setData("{\"code\":"+rst.getCode()+",\"msg\":\"" + rst + "\"}")
				.setCode(0);
	}
	
	public BizResult editNodes(Map<String,String> input){
		//删除所有的节点
		daoSupport.delete("wf_node", "n_tpl ="+input.get("n_tpl"));
		return addNodes(input);
	}
	
	public BizResult addNodes(Map<String,String> input){
		int length = Integer.parseInt(input.get("length"));
		//未设置任何节点
		if(length<1){
			return rst.setType(BizResult.ECHO)
					.setData("NO DATA")
					.setCode(0);
		}
		List<Map<String,String>> es = new ArrayList<Map<String,String>>(); 
		for(int i = 0 ; i<length ; i++){
			String s = input.get("["+i+"]");
			String[] arr_s = s.split("~");
			Map<String,String> e = new HashMap<String,String>();
			for(String as : arr_s){
				String[] kv = as.split(":");
				//未设置值
				if(kv.length<2){
					e.put(kv[0],null);
				}else{
					e.put(kv[0], kv[1]);
				}
			}
			es.add(e);
		}
		int rows = this.daoSupport.insert( "wf_node",es.toArray(new Map[]{}));
		return rst.setType(BizResult.ECHO)
				.setData(rows)
				.setCode(0);
	}
	
	public BizResult delete(Map<String,String> input) throws Throwable{
		daoSupport.delete("wf_node", "n_tpl ="+input.get("id"));
		daoSupport.delete("wf_tpl", "t_id ="+input.get("id"));
		return rst.setCode(0);
	}
	
	public BizResult list(Map<String,String> input) throws Throwable{
		Map<String,Object> m = this.daoSupport.findOne("sys_model", "m_id", "m_name = 'wf-tpl'");
		input.put("m_id", m.get("m_id").toString());
		rst = super.list(input);
		rst.setPage("WIDGETS/WF/list.jsp");
		return rst;
	}
	
	//推进流程
	public BizResult process(Map<String,String> input) throws Throwable{
		//input.put(", value)
		
		//获取流程实例的参数
		//1.实例ID
		String entry_id = input.get("p_entry");
		//2.节点代码
		int node = Integer.parseInt(input.get("p_node"));
		String result = "";
//		Map<String,Object> old_entry = this.daoSupport.query("wf_entry",null,"e_id = "+input.get("e_id"));
//		node = Integer.parseInt(old_entry.get("e_node").toString());
		//处理节点的流向
		result = input.get("p_deal_result");
		if("stop".equals(result)){
			//业务终止
			Map<String,String> entry = new HashMap<String,String>();
			entry.put("e_update_date", TimeUtil.getNow());
			entry.put("e_status", "stop");
			this.daoSupport.update(entry, "e_id = "+entry_id, "wf_entry");
		}else if("reject".equals(result)){
			//驳回
			//node -= 1;
			if(node<1){
				//发起者无法驳回
			}else{
				
				Map<String,Object> prev_node = this.daoSupport.findOne("wf_process",null,"p_node = "+node +" and p_entry = "+entry_id );
				//获取前一个节点的用户
				Map<String,String> entry = new HashMap<String,String>();
				entry.put("e_next_user", prev_node.get("p_deal_user").toString());
				node -= 1;
				entry.put("e_node", String.valueOf(node));
				entry.put("e_update_date", TimeUtil.getNow());
				this.daoSupport.update(entry, "e_id = "+entry_id, "wf_entry");
			}
		}else{
			//通过
			
			Map<String,String> entry = new HashMap<String,String>();
			
			entry.put("e_update_date", TimeUtil.getNow());
			//如果是最后一个节点，通过则完成流程
			Map<String,Object> max_code = this.daoSupport.findOne("wf_node","max(n_code) maxcode","n_tpl =(select e_tpl from wf_entry where e_id= "+entry_id+")");
			int maxcode = Integer.parseInt(max_code.get("maxcode").toString());
			
			if(node >= maxcode){
				entry.put("e_status", "approved");
			}else{
				node += 1;
				//流程中的节点
				entry.put("e_next_user", input.get("p_next_user"));
				entry.put("e_node", String.valueOf(node));
			}
			this.daoSupport.update(entry, "e_id = "+entry_id, "wf_entry");
		}
		Map<String,Object> user = rst.getSissAttribute(GlobalKey.USER);
		input.put("p_entry",entry_id);
		input.put("p_deal_user", user.get("ui_id").toString());
		input.put("p_node", String.valueOf(node));
		input.put("p_deal_date",TimeUtil.getNow());
		this.daoSupport.insert( "wf_process",input);
		input.put("t","todo");
		return matters(input);
	}
	
	public BizResult deal(Map<String,String> input) throws Throwable{
		String e_id = input.get("e_id");
		rst.setReqAttribute("p_entry", e_id);
		rst.setReqAttribute("t", input.get("t"));
		Map<String,Object> e = this.daoSupport.findOne("wf_entry",null,"e_id = "+e_id);
		String tpl_id = e.get("e_tpl").toString();
//		String next_user = e.get("e_next_user").toString();
		String node = e.get("e_node").toString();
		rst.setReqAttribute("p_node", node);
		//加载处理结果数据源
		rst.setReqAttribute("result", this.getDataSource("ds_name", "流程处理结果"));
		//获取下一节点的审批部门的用户
		//判断是否是最终的节点
		//select n_cur_obs from wf_node where 
		Map<String,Object> nodes = daoSupport.findOne("wf_node", "n_cur_obs", "n_tpl = "+tpl_id+" and n_prev_code = '"+node+"'");
		if(nodes != null && nodes.containsKey("n_cur_obs")){
			rst.setReqAttribute("next_users", daoSupport.find("usr_userinfo ui,usr_obs o","ui.ui_id as k,CONCAT(o.o_name,'-',ui.ui_nickname) as v","ui.ui_dept = o.o_id and ui.ui_dept = "+nodes.get("n_cur_obs"),null));
		}
			
//		rst.setReqAttribute(GlobalKey.WF_CHECK, "c?s=tpl&o=detail&m_id="+e.get("e_model_id").toString()+"&key="+e.get("e_ref_id").toString());
		rst.setReqAttribute("logs",this.daoSupport.find("wf_process p,usr_userinfo u" , "p.*,u.*", "p.p_deal_user = u.ui_id and p.p_entry = "+e_id, "p.p_deal_date desc"));
		rst.setReqAttribute("remarks",this.daoSupport.find("wf_node",null, "n_tpl = "+tpl_id, "n_code asc"));
		return rst.setCode(0).setType(BizResult.REDIRECT).setPage("WIDGETS/WF/process.jsp");
	}
	
	public BizResult matters(Map<String,String> input){
		String t = input.get("t");
		Map<String,Object> user = rst.getSissAttribute(GlobalKey.USER);
		if("todo".equals(t)){
			//待办事宜
			rst.setReqAttribute("list", this.daoSupport.find("wf_entry", "e_id,e_title,e_update_date", 
					"e_status in ('process','start') and e_next_user = "+user.get("ui_id"), "e_update_date desc"));
			rst.setReqAttribute("p", "todo");
		}else if(("did").equals(t)){
			//已办事宜	
			rst.setReqAttribute("list", this.daoSupport.find("wf_entry",null,
					"e_id in(select p_entry from wf_process " +
					"where p_deal_user = "+user.get("ui_id")+") ","e_update_date desc"));
			rst.setReqAttribute("p", "did");
		}else if(("all").equals(t)){
			//所有事宜
			rst.setReqAttribute("list", this.daoSupport.find("wf_entry", "e_id,e_title,e_update_date,e_model_id,e_ref_id", 
					"e_status in ('process','start')", "e_update_date desc"));
			rst.setReqAttribute("p", "all");
		}
		
		return rst.setCode(0).setType(BizResult.REDIRECT).setPage("WIDGETS/WF/entrylist.jsp");
	}
	
	public BizResult create(Map<String,String> input)throws Throwable{
		//创建流程的操作
		//加载面板
		List<Map<String,Object>> wf_list = this.getDataSource("ds_name","工作流模板");
		rst.setReqAttribute("wf_list",wf_list );
		return rst.setCode(0).setType(BizResult.REDIRECT).setPage("WIDGETS/WF/form.jsp");
	}
	public BizResult createMatter(Map<String,String> input)throws Throwable{
		return super.createMatter(input);
	}
	
}
